﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Mindfor.Web
{
	/// <summary>
	/// Enables ReturnUrl tracking.
	/// Replaces null one with ReferrerUrl.
	/// Sets it to ViewData.
	/// </summary>
	public class ReturnUrlEnableAttribute : FilterAttribute, IActionFilter
	{
		public void OnActionExecuting(ActionExecutingContext filterContext)
		{
			// get return url from request
			string returnUrl = filterContext.HttpContext.Request["returnUrl"];

			// if return url is null or empty then set it to refferer
			if (String.IsNullOrEmpty(returnUrl))
			{
				Uri referrer = filterContext.HttpContext.Request.UrlReferrer;
				if (referrer != null)
					returnUrl = referrer.PathAndQuery;
			}

			// pass return url to controller view data
			filterContext.Controller.ViewData["returnUrl"] = returnUrl;
		}

		public void OnActionExecuted(ActionExecutedContext filterContext)
		{
		}
	}
}
